<template>
  <div class="w-full h-full flex flex-col">
    <!-- 上传区域 -->
    <div @dragover.prevent="dragActive = true" @dragleave="dragActive = false" @drop.prevent="handleDrop" :class="[
      'flex-1 border-2 border-dashed rounded-xl p-4 lg:p-6 text-center cursor-pointer transition-all',
      dragActive ? 'border-blue-500 bg-blue-50' : 'border-gray-300 hover:border-gray-400',
      disabled ? 'opacity-50 cursor-not-allowed' : ''
    ]" @click="!disabled && triggerFileInput()">
      <input ref="fileInput" type="file" :accept="accept" multiple class="hidden" :disabled="disabled"
        @change="handleFileChange">

      <div class="h-full flex flex-col items-center justify-center space-y-3" v-if="maxFiles <= 1 ? !previewUrl : true">
        <div>
          <span class="font-medium text-blue-600">点击上传</span>
          <span class="text-gray-600"> 或拖放图片到此处</span>
        </div>
        <p class="text-sm text-gray-500">
          支持 {{ acceptDisplay }} 格式 (最大 {{ maxSize }}MB)
        </p>
      </div>

      <div class="h-full w-full relative  p-4 lg:p-6 " v-if="maxFiles <= 1 && previewUrl">
        <div class="absolute inset-0 flex items-center justify-center p-1">
          <img :src="previewUrl" class="max-w-full max-h-full object-contain" />
        </div>
      </div>
    </div>

    <!-- 错误提示 -->
    <!-- <div v-if="errorMessage" class="mt-2 text-red-500 text-sm">
      {{ errorMessage }}
    </div> -->

    <!-- 预览区域 -->
    <div v-if="maxFiles > 1" class="mt-4 flex-1 overflow-auto">
      <!-- <h3 class="font-medium text-gray-700 mb-2">已选择 {{ files.length }}/{{ maxFiles }} 张图片</h3> -->

      <div class="grid grid-cols-3 sm:grid-cols-4 lg:grid-cols-5 gap-2 lg:gap-3">
        <div v-for="(file, index) in files" :key="index" class="relative group border rounded-lg overflow-hidden">
          <img :src="getPreviewUrl(file)" :alt="file.name" class="w-full aspect-square object-cover">

          <div class="p-1 text-xs truncate">
            {{ truncateFilename(file.name) }}
          </div>

          <button v-if="!disabled" @click.stop="removeFile(index)"
            class="absolute top-1 right-1 bg-red-500 text-white rounded-full p-1 opacity-0 group-hover:opacity-100 transition-opacity text-xs">
            删除
          </button>
        </div>
      </div>

      <!-- 操作按钮 -->
      <div class="mt-4 flex justify-between space-x-3">
        <button v-if="!disabled" @click="clearFiles"
          class="flex-1 px-1 py-1 border border-gray-300 rounded-md text-gray-700 hover:bg-gray-50">
          清空
        </button>

        <button @click="uploadFiles" :disabled="uploading || disabled" :class="[
          'flex-1 px-1 py-1 rounded-md text-white flex items-center justify-center',
          uploading || disabled ? 'bg-blue-400 cursor-not-allowed' : 'bg-blue-600 hover:bg-blue-700'
        ]">
          <span v-if="!uploading">开始上传</span>
          <span v-else>上传中...</span>
        </button>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed } from 'vue'

// 定义Props接收父组件传值
const props = defineProps({
  uploadUrl: {
    type: String,
    default: ''
  },
  // 最大上传数量
  maxFiles: {
    type: Number,
    default: 1
  },
  // 单个文件最大尺寸(MB)
  maxSize: {
    type: Number,
    default: 20
  },
  // 接受的文件类型
  accept: {
    type: String,
    default: 'image/*'
  },
  // 是否禁用
  disabled: {
    type: Boolean,
    default: false
  }
})

// 定义事件发射
const emit = defineEmits([
  'upload-start',    // 上传开始
  'upload-success',  // 上传成功
  'upload-error',    // 上传失败
  'update:files',    // 文件更新
  'file-added',      // 文件添加
  'file-removed'     // 文件移除
])


// 响应式状态
const fileInput = ref<HTMLInputElement | null>(null)
const files = ref<File[]>([])
const dragActive = ref(false)
const uploading = ref(false)
const errorMessage = ref<string | null>(null)
const previewUrl = ref<string | undefined>(undefined)

previewUrl.value = props.uploadUrl
// 计算属性：显示可接受的文件类型
const acceptDisplay = computed(() => {
  if (props.accept === 'image/*') return 'JPG, PNG, GIF'
  return props.accept.split(',').join(', ')
})

// 处理文件选择
const handleFileChange = (e: Event) => {
  const input = e.target as HTMLInputElement
  if (input.files?.length) {
    processFiles(Array.from(input.files))
  }
}

// 处理拖放文件
const handleDrop = (e: DragEvent) => {
  debugger
  if (props.disabled) return
  dragActive.value = false
  if (e.dataTransfer?.files.length) {
    processFiles(Array.from(e.dataTransfer.files))
  }
}

// 处理添加的文件
const processFiles = (newFiles: File[]) => {
  errorMessage.value = null



  // 过滤非图片文件
  const validFiles = newFiles.filter(file => {
    const isValidType = props.accept === 'image/*'
      ? file.type.startsWith('image/')
      : props.accept.split(',').includes(file.type)

    const isValidSize = file.size <= props.maxSize * 1024 * 1024
    return isValidType && isValidSize
  })

  // 检查无效文件
  const invalidFiles = newFiles.filter(file => {
    const isValidType = props.accept === 'image/*'
      ? file.type.startsWith('image/')
      : props.accept.split(',').includes(file.type)

    return !isValidType || file.size > props.maxSize * 1024 * 1024
  })

  if (invalidFiles.length > 0) {
    const invalidNames = invalidFiles.map(f => f.name).join(', ')
    errorMessage.value = `以下文件不符合要求: ${invalidNames}`
  }
  // 检查文件数量限制
  if (props.maxFiles == 1 && newFiles.length >= 1) {
    files.value = [...validFiles]
  } else if (files.value.length + newFiles.length > props.maxFiles) {
    errorMessage.value = `最多只能上传${props.maxFiles}个文件`
    return
  } else {
    files.value = [...files.value, ...validFiles]
  }
  // 添加到文件列表
  // emit('update:files', files.value)
  // emit('file-added', validFiles)
  uploadFiles()
  // 重置文件输入
  if (fileInput.value) {
    fileInput.value.value = ''
  }
}

// 获取预览URL
const getPreviewUrl = (file: File) => {
  return URL.createObjectURL(file)
}

// 删除单个文件
const removeFile = (index: number) => {
  const removed = files.value.splice(index, 1)
  emit('update:files', files.value)
  emit('file-removed', removed[0])
}

// 清空所有文件
const clearFiles = () => {
  files.value = []
  errorMessage.value = null
  emit('update:files', [])
}

// 触发文件选择对话框
const triggerFileInput = () => {
  if (fileInput.value) {
    fileInput.value.click()
  }
}

// 文件名截断
const truncateFilename = (name: string, maxLength = 15) => {
  if (name.length <= maxLength) return name
  return `${name.substring(0, maxLength)}...`
}

// 上传文件
const uploadFiles = async () => {
  if (props.disabled) return
  if (!files.value.length) {
    errorMessage.value = '请先选择图片'
    return
  }

  try {
    uploading.value = true
    errorMessage.value = null

    const formData = new FormData()
    files.value.forEach(file => {
      formData.append('files', file)
    })

    // 使用Nuxt的$fetch API 
    const response = await $fetch<any>('/api/upload', {
      method: 'POST',
      body: formData
    })
    let data = response.data
    let url = data[0].filePath
    previewUrl.value = url
    // 上传成功处理
    console.log('上传成功:', response)
    emit('upload-success', {
      files: files.value,
      response
    })

    // 根据父组件需求决定是否自动清空
    // clearFiles()
  } catch (error: any) {
    // 错误处理
    console.error('上传失败:', error)
    errorMessage.value = error.message || '上传失败，请重试'
    emit('upload-error', {
      error,
      files: files.value
    })
  } finally {
    uploading.value = false
  }
}



// 暴露方法给父组件调用
defineExpose({
  clearFiles,
  triggerUpload: uploadFiles,
  getFiles: () => files.value
})
</script>